<?php

namespace App\Transformers;

use App\Models\Comment;
use App\Models\CommentsLike;

class CommentTransformer extends BaseTransformer
{
    protected $defaultIncludes = ['children'];

    private $user;

    public function __construct(array $select = [], $user = null)
    {
        $this->user = $user;

        parent::__construct($select);
    }

    public function transform(Comment $model)
    {
        return [
            'id' => $model->id,
            'user_id' => $model->user_id,                                                                   #评论者id
            'user_type' => getModelName($model->user_type),                                                 #评论者的所属Model
            'user_nick_name' => $model->user->nick_name ?: $model->user->username,                          #评论者姓名
            'user_avatar' => image_url($model->user->avatar),                                                #评论者头像
//            'object_id' => $model->object_id,                                                               #被评论对象的id
//            'object_type' => getModelName($model->object_type),                                             #被评论对象的所属Model
            'content' => $model->content,                                                                   #评论内容
            'like_amount' => $model->like_amount,                                                           #点赞量
            'is_likes' => $this->isLike($model->id),
            'created_at' => $model->created_at->toDateTimeString(),
        ];
    }

    public function includeChildren(Comment $model)
    {
        return $this->collection($model->allChildren, new CommentTransformer([], $this->user));
    }

    public function isLike($comment_id)
    {
        $result = false;

        if ($this->user) {
            $result = !!CommentsLike::where('comment_id', $comment_id)->where('user_id', $this->user->id)->first();
        }

        return $result;
    }
}
